package com.atguigu.gmall.order.mq;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.config.mq.service.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.msg.express.OrderExpressMsg;
import com.atguigu.gmall.order.service.ExpressService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-27 20:17
 **/
@Slf4j
@Service
public class ExpressListener {
    @Autowired
    MqService mqService;
    @Autowired
    ExpressService expressService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = MqConst.ORDER_EXPRESS_QUEUE, durable = "true", exclusive = "false", autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.ORDER_EVENT_EXCHANGE, durable = "true", autoDelete = "false", type = "topic"),
                    key = MqConst.ORDER_EXPRESS_RK
            )
    })
    public void sendExpress(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        OrderExpressMsg orderExpressMsg = mqService.getMessageContent(message, OrderExpressMsg.class);
        try {
            log.info("订单{}，正在生成电子面单", orderExpressMsg.getOrderId());
            JSONObject jsonObject = expressService.generateExpressOrderE(orderExpressMsg.getOrderId(), orderExpressMsg.getUserId());
            log.info("得到电子面单数据：{}", jsonObject);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            mqService.retry(message, channel, MqConst.ORDER_RETRY_COUNT);
        }
    }
}
